package com.android.manghe.view;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.android.manghe.R;
import com.android.manghe.box.activity.UnpackingActivity;
import com.android.manghe.box.adapter.Gift2UltraPagerAdapter;
import com.android.manghe.box.model.BoxModel;
import com.android.manghe.box.model.BoxPrizeModel;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.webview.ERefreshWebType;
import com.android.manghe.common.webview.WebViewActivity;
import com.android.manghe.common.webview.WebViewParameter;
import com.android.manghe.config.Config;
import com.android.manghe.user.activity.LoginActivity;
import com.android.manghe.utils.VoicePlayer;
import com.android.manghe.utils.WindowUtils;
import com.android.manghe.view.popWindow.BoxGoodsPopWindow;
import com.google.android.material.tabs.TabLayout;
import com.tmall.ultraviewpager.UltraViewPager;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/11/01 13:57
 * desc   :
 */
public class OpenBoxLayout extends FrameLayout {

    private Context mContext;
    private RelativeLayout mLayoutFree, mLayoutOpenBox, mLayoutFindBox, mLayoutChange;
    private TextView mTvCoin;

    private List<BoxModel.DataBean> mBoxList;
    private BoxModel.DataBean mCurrentBox;
    private AnimatorSet animatorSet;
    private BoxGiftBubbleView mBubbleView;
    private Activity mActivity;
    private UltraViewPager mUltraViewPager;
    private Gift2UltraPagerAdapter mPageAdapter;

    private TabLayout mTabLayout;
    private ImageView mImgMusic, mImgPlayRule;
    private boolean mIsPlay = true;
    private IOpenBoxLayoutListener mListener;
    private BoxGiftsUpView mBoxGiftUpView;

    public void setListener(IOpenBoxLayoutListener listener) {
        this.mListener = listener;
    }


    public BoxModel.DataBean getCurrentBox() {
        return mCurrentBox;
    }

    public OpenBoxLayout(Context context) {
        super(context);
        initView(context);
    }

    public void setmIsPlay(boolean mIsPlay) {
        this.mIsPlay = mIsPlay;
    }

    public boolean ismIsPlay() {
        return mIsPlay;
    }

    public OpenBoxLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }


    public void setActivity(Activity activity) {
        this.mActivity = activity;
    }

    private void initView(Context context) {
        mContext = context;
        View itemView = null;
        if (WindowUtils.getRawScreenH(mContext) > 2000) {
            itemView = LayoutInflater.from(context).inflate(R.layout.layout_open_box_large, null);
        } else if (WindowUtils.getRawScreenW(mContext) == 900 && WindowUtils.getRawScreenH(mContext) == 1600) {
            itemView = LayoutInflater.from(context).inflate(R.layout.layout_open_box_900_1600, null);
        } else {
            itemView = LayoutInflater.from(context).inflate(R.layout.layout_open_box, null);
        }
        addView(itemView);
        animatorSet = new AnimatorSet();
        mLayoutFindBox = itemView.findViewById(R.id.id_re_find_box);
        mLayoutFree = itemView.findViewById(R.id.id_re_try);
        mLayoutOpenBox = itemView.findViewById(R.id.id_re_open_box);
        mLayoutChange = itemView.findViewById(R.id.id_re_change);
        mTvCoin = itemView.findViewById(R.id.id_tv_coin);
        mBubbleView = itemView.findViewById(R.id.BubbleView);
        mUltraViewPager = itemView.findViewById(R.id.bannerViewPager);
        mTabLayout = itemView.findViewById(R.id.tabLayout);
        mImgMusic = itemView.findViewById(R.id.id_img_music);
        mImgPlayRule = itemView.findViewById(R.id.id_img_play_rule);
        mBoxGiftUpView = itemView.findViewById(R.id.boxGiftsUpView);

        initRecyclerView();
        startAnimator();
        setViewPagerScrollSpeed();

        //打开盒子
        mLayoutOpenBox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserHolder.getUserInfo(mContext) != null) {
                    if (mCurrentBox != null) {
                        if (mListener != null) {
                            mListener.onClick(v);
                        }
                    }
                } else {
                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
                }
            }
        });

        //免费试玩
        mLayoutFree.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentBox != null) {
                    Intent intent = new Intent(mActivity, UnpackingActivity.class);
                    intent.putExtra("BoxListModel", mCurrentBox);
                    mActivity.startActivity(intent);
                    stopMusic_2();
                }
            }
        });

        //查找盒子
        mLayoutFindBox.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentBox != null && mActivity != null) {
                    BoxGoodsPopWindow popWindow = new BoxGoodsPopWindow(mActivity, mCurrentBox, mCurrentBox.goods_list);
                    popWindow.showPopWindow(v);
                }
            }
        });

        //换一盒
        mLayoutChange.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (mUltraViewPager != null) {
                        mUltraViewPager.getViewPager().setCurrentItem(mUltraViewPager.getNextItem(), true);
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
        });

        mImgMusic.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIsPlay) {
                    stopMusic();
                } else {
                    startMusic();
                }
            }
        });

        //玩法规则
        mImgPlayRule.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                WebViewParameter parameters = new WebViewParameter.WebParameterBuilder()
                        .setUrl(Config.BOX_PLAY_RULE)
                        .setShowProgress(true)
                        .setCanHistoryGoBackOrForward(true)
                        .setReloadable(true)
                        .setShowWebPageTitle(false)
                        .setReloadType(ERefreshWebType.ClickRefresh)
                        .setCustomTitle("玩法说明")
                        .build();

                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra("parameters", parameters);
                mContext.startActivity(intent);
            }
        });
    }


    /**
     * 设置ViewPager切换速度
     */
    private void setViewPagerScrollSpeed() {
        try {
            Field mScroller = null;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(mUltraViewPager.getViewPager().getContext());
            mScroller.set(mUltraViewPager.getViewPager(), scroller);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();

        }
    }


    /**
     * 开始动画
     */
    private void startAnimator() {
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(mLayoutOpenBox, "scaleX", 1f, 1.16f, 1f);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(mLayoutOpenBox, "scaleY", 1f, 1.16f, 1f);
        animatorX.setRepeatCount(ValueAnimator.INFINITE);
        animatorY.setRepeatCount(ValueAnimator.INFINITE);
        animatorSet.setDuration(1500);
        animatorSet.play(animatorX).with(animatorY);
        animatorSet.start();

    }

    private void initRecyclerView() {
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setSelectedTabStyle(mTabLayout, mTabLayout.getSelectedTabPosition());
                mCurrentBox = mBoxList.get(mTabLayout.getSelectedTabPosition());
                if (mUltraViewPager != null) {
                    mUltraViewPager.getViewPager().setCurrentItem(mTabLayout.getSelectedTabPosition(), true);
                }
                mBubbleView.stop();
                giftsUp();
                setBoxCoin();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }

    private View getTabView(int position, List<BoxModel.DataBean> list) {
        View view = View.inflate(mContext, R.layout.item_box_type, null);
        view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView tv = view.findViewById(R.id.id_tv_name);
        tv.setText(list.get(position).name);
        return view;
    }

    private void setSelectedTabStyle(TabLayout tabLayout, int position) {
        try {
            TextView tv = null;
            RelativeLayout re = null;
            for (int i = 0; i < tabLayout.getTabCount(); i++) {
                TabLayout.Tab tab = tabLayout.getTabAt(i);
                tv = tab.getCustomView().findViewById(R.id.id_tv_name);
                tv.setTextColor(ContextCompat.getColor(mContext, R.color.colorFont33));
                re = tab.getCustomView().findViewById(R.id.ly_body);
                re.setBackgroundResource(R.color.white);
            }
            TabLayout.Tab selectedTab = tabLayout.getTabAt(position);
            tv = selectedTab.getCustomView().findViewById(R.id.id_tv_name);
            re = selectedTab.getCustomView().findViewById(R.id.ly_body);
            re.setBackgroundResource(R.mipmap.open_box_bg_7);
            tv.setTextColor(ContextCompat.getColor(mContext, R.color.white));


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setBoxCoin() {
        if (mCurrentBox != null && mCurrentBox.prices != null && mCurrentBox.prices._$1 != null) {
            mTvCoin.setText("￥" + mCurrentBox.prices._$1.sell_price + "/个");
        }
    }

    /**
     * 修改导航栏
     *
     * @param list
     */
    public void updateTab(List<BoxModel.DataBean> list) {
        this.mBoxList = list;
        mCurrentBox = mBoxList.get(0);
        mBubbleView.stop();
        giftsUp();
        setBoxCoin();

        //展示上面的滑动层
        mPageAdapter = new Gift2UltraPagerAdapter(mContext, list);
        mUltraViewPager.setAdapter(mPageAdapter);
        mUltraViewPager.setInfiniteLoop(true);
        mUltraViewPager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL);
        mUltraViewPager.setCurrentItem(0);
        mUltraViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mUltraViewPager.setCurrentItem(position, true);
                setSelectedTabStyle(mTabLayout, mUltraViewPager.getCurrentItem());
                mTabLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mTabLayout.getTabAt(mUltraViewPager.getCurrentItem()).select();
                    }
                }, 100);
                mBubbleView.stop();
                giftsUp();

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        //展示下面的滑动层
        mTabLayout.removeAllTabs();
        for (int i = 0; i < list.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setCustomView(getTabView(i, list)));
        }
        mTabLayout.post(new Runnable() {
            @Override
            public void run() {
                mTabLayout.scrollTo(0, 0);
            }
        });


    }

    /**
     * 更改获奖名单
     *
     * @param list
     */
    public void updatePrize(List<BoxPrizeModel.DataBean.ListBean> list) {
        mBoxGiftUpView.stop();
        mBoxGiftUpView.setDrawableList(list)
                .setAnimationDelay(3000)
                .setRiseDuration(4 * 1000)
                .setMinHeartNum(2)
                .setMaxHeartNum(2)
                .setScaleAnimation(1, 0.5f);
        mBoxGiftUpView.startAnimation(1000000000);
    }

    /**
     * 礼物开始起飞
     */
    public void giftsUp() {
        if (mCurrentBox != null) {
            mBubbleView.setDrawableList(splitList(mCurrentBox.goods_list, 3))
                    .setRiseDuration(6 * 1000);
            mBubbleView.startAnimation(1000000000);

        }
    }

    private List<List<BoxModel.DataBean.GoodsListBean>> splitList(List<BoxModel.DataBean.GoodsListBean> messagesList, int groupSize) {
        int length = messagesList.size();
        // 计算可以分成多少组
        int num = (length + groupSize - 1) / groupSize; // TODO
        List<List<BoxModel.DataBean.GoodsListBean>> newList = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            // 开始位置
            int fromIndex = i * groupSize;
            // 结束位置
            int toIndex = (i + 1) * groupSize < length ? (i + 1) * groupSize : length;
            newList.add(messagesList.subList(fromIndex, toIndex));
        }
        return newList;
    }


    /**
     * 停止获奖名单上升
     */
    public void stopBoxGift() {
        mBoxGiftUpView.stop();
    }


    /**
     * 开启音乐
     */
    public void startMusic() {
        mImgMusic.setImageResource(R.mipmap.icon_box_music_black);
        VoicePlayer.getInstance().startPlay();
        VoicePlayer.getInstance().setLoop();
        starFreshenAnimation(mImgMusic);
        mIsPlay = true;
    }

    /**
     * 停止音乐
     */
    public void stopMusic() {
        VoicePlayer.getInstance().pausePlay();
        mImgMusic.setImageResource(R.mipmap.icon_box_music_gray);
        stopFreshenAnimation(mImgMusic);
        mIsPlay = false;
    }

    public void stopMusic_2() {
        VoicePlayer.getInstance().pausePlay();
        stopFreshenAnimation(mImgMusic);
    }

    private void starFreshenAnimation(ImageView imageView) {
        Animation circle_anim = AnimationUtils.loadAnimation(mContext, R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
        circle_anim.setInterpolator(interpolator);
        imageView.startAnimation(circle_anim);  //开始动画
    }


    private void stopFreshenAnimation(ImageView imageView) {
        imageView.clearAnimation();
    }

    public interface IOpenBoxLayoutListener {
        void onClick(View view);
    }

}
